//
//  WmcSettingHeaderView.swift
//  YPWatermarkCamera
//
//  Created by Json on 2023/7/6.
//

import UIKit
import RxRelay
import YPGraphicEngine

extension WmcSettingHeaderView {
    enum Action {
        /// 拍照画幅
        case aspect
        /// 延时拍照
        case delay(time: DelayTime)
        /// 分辨率
        case resolution
        /// 清晰度
        case articulation(value: YPGEVideoBuffer.Articulation)
        /// 邀请朋友
        case invite
        /// 团队相册
        case album
        /// 加群
        case joinGroup
    }
    
}

class WmcSettingHeaderView: WmcBaseView {
    
    typealias DelayTime = WmcDelayBtn.DelayTime
    typealias AspectRatio = YPGESunglasses.AspectRatio

    /// stackView
    private lazy var stackView: UIStackView = {
        let stackV = UIStackView()
        stackV.axis = .vertical
        stackV.spacing = spacing
        stackV.distribution = .fill
        stackV.alignment = .fill
        return stackV
    }()
    /// topView
    private lazy var topView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.wmc_white_FFFFFF
        view.layer.cornerRadius = 8.0
        view.clipsToBounds = true
        return view
    }()
    /// topStackView
    private lazy var topStackView: UIStackView = {
        let stackV = UIStackView()
        stackV.axis = .horizontal
        stackV.spacing = 30.0.wmc_autoHor
        stackV.distribution = .fillEqually
        stackV.alignment = .fill
        return stackV
    }()
    
    /// 拍照画幅
    private lazy var aspectRatioBtn: WmcStyleButton = {
        let btn = makeButton(title: "拍照画幅", imageName: "icon_image_aspect_32")
        return btn
    }()
    /// 延时拍照
    private lazy var delayBtn: WmcStyleButton = {
        let btn = makeButton(title: "延时拍照", imageName: "icon_delay_32")
        return btn
    }()
    /// 滤镜
    private lazy var imageFilterBtn: WmcStyleButton = {
        let btn = makeButton(title: "滤镜", imageName: "icon_image_filter_32")
        return btn
    }()
    /// 分辨率
    private lazy var resolutionBtn: WmcStyleButton = {
        let btn = makeButton(title: "分辨率", imageName: "icon_resolution_32")
        return btn
    }()
    
    /// 清晰度
    private lazy var articulationBtn: WmcStyleButton = {
        let btn = makeButton(title: "清晰度", imageName: "icon_articulation_720P_32")
        return btn
    }()
    
    /// bottomStackView
    private lazy var bottomStackView: UIStackView = {
        let stackV = UIStackView()
        stackV.axis = .horizontal
        stackV.spacing = 8.0.wmc_autoHor
        stackV.distribution = .fillEqually
        stackV.alignment = .fill
        return stackV
    }()
    /// 邀请朋友
    private lazy var inviteItemView: WmcSettingBusinessItemView = {
        let view = WmcSettingBusinessItemView()
        view.image = "icon_friend_36".wmc_image
        view.title = "邀请朋友"
        view.subTitle = "免费使用"
        return view
    }()
    /// 加用户群
    private lazy var joinItemView: WmcSettingBusinessItemView = {
        let view = WmcSettingBusinessItemView()
        view.image = "icon_join_group_36".wmc_image
        view.title = "加用户群"
        view.subTitle = "免费提需求"
        return view
    }()
    /// 团队相册
    private lazy var albumItemView: WmcSettingBusinessItemView = {
        let view = WmcSettingBusinessItemView()
        view.image = "icon_album_36".wmc_image
        view.title = "团队相册"
        view.subTitle = "实时同步"
        return view
    }()
    private let viewWidth: CGFloat
    private let topStackH = 76.0.wmc_autoHor
    private let spacing = 8.0.wmc_autoHor
    private let bottomStackH = 64.0.wmc_autoHor
    private let disableColor = UIColor.wmc_grayH13_ACAEAF
   
    /// 延时拍照时间
    var delayTime: DelayTime = .none {
        didSet {
            delayBtn.setTitle(delayTime.info.title, for: .normal)
            delayBtn.setImage(delayTime.info.image, for: .normal)
            delayBtn.setImage(delayTime.info.image.yp.set(tintColor: disableColor), for: .disabled)
            let titleColor = delayTime == .none ? UIColor.wmc_grayH2_323233 : UIColor.wmc_mainTheme
            delayBtn.setTitleColor(titleColor, for: .normal)
        }
    }
    /// 清晰度
    var articulation: YPGEVideoBuffer.Articulation = ._720p {
        didSet {
            let image: UIImage
            switch articulation {
            case ._1080p:
                image = "icon_articulation_1080P_32".wmc_image
            case ._720p:
                image = "icon_articulation_720P_32".wmc_image
            case ._540p:
                image = "icon_articulation_540P_32".wmc_image
            default:
                image = UIImage()
            }
            set(image: image, for: articulationBtn)
        }
    }
    
    
    /// 画幅比例
    var aspectRatio: AspectRatio = .ar_4_3 {
        didSet {
            aspectRatioBtn.setImage(aspectRatio.info.image, for: .normal)
        }
    }
    
    /// 功能模式
    var functionMode: WmcButtonItemType.HomeFunctionMode = .photo {
        didSet {
            reloadTopActions()
        }
    }
    
    /// 是否关注了公众号
    var isSubscribed: Bool = false {
        didSet {
            reloadBottomActions()
        }
    }

    /// 点击按钮回调
    let buttonAction: PublishRelay<Action> = .init()
    
    // MARK: Init
    init(width: CGFloat = Wmc_screenWidth) {
        self.viewWidth = width
        super.init(frame: .zero)
    }
    
    public required convenience init() {
        fatalError("init() has not been implemented")
    }
    
    // MARK: UI
    
    override func makeUI() {
        super.makeUI()
        backgroundColor = .clear
        // stackView
        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.top.left.equalToSuperview()
            make.width.equalTo(self.viewWidth)
        }
        // topView
        stackView.addArrangedSubview(topView)
        topView.snp.makeConstraints { make in
            make.height.equalTo(topStackH)
        }
        // topStackView
        topView.addSubview(topStackView)
        topStackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        // bottomStackView
        stackView.addArrangedSubview(bottomStackView)
        bottomStackView.snp.makeConstraints { make in
            make.height.equalTo(bottomStackH)
        }
        
        // 默认值
        self.functionMode = .photo
        self.isSubscribed = false
        self.delayTime = .none
        self.aspectRatio = .ar_4_3
        self.articulation = ._720p
    }
    
    // MARK: Bind Action
    
    override func bindViewAction() {
        super.bindViewAction()
        // 点击拍照画幅
        aspectRatioBtn.rx.tap.map { Action.aspect }.bind(to: buttonAction).disposed(by: rx.disposeBag)
        // 点击延时拍照
        delayBtn.rx.tap.map {
            [weak self] in
            self?.switchDelayTime()
            return Action.delay(time: self?.delayTime ?? .none)
        }.bind(to: buttonAction).disposed(by: rx.disposeBag)
        // 点击分辨率
        resolutionBtn.rx.tap.map { Action.resolution }.bind(to: buttonAction).disposed(by: rx.disposeBag)
        // 点击清晰度
        articulationBtn.rx.tap.map {  [weak self] in
            self?.switchArticulation()
            return Action.articulation(value: self?.articulation ?? ._720p)
        }.bind(to: buttonAction).disposed(by: rx.disposeBag)
        // 点击邀请朋友
        inviteItemView.rx.tapGesture().when(.recognized).map { _ in Action.invite }.bind(to: buttonAction).disposed(by: rx.disposeBag)
        // 点击加入群组
        joinItemView.rx.tapGesture().when(.recognized).map { _ in Action.joinGroup }.bind(to: buttonAction).disposed(by: rx.disposeBag)
        // 点击团队相册
        albumItemView.rx.tapGesture().when(.recognized).map { _ in Action.album }.bind(to: buttonAction).disposed(by: rx.disposeBag)
    }
}

extension WmcSettingHeaderView {
    
    func fittedHeight() -> CGFloat {
        let height = topStackH + spacing + bottomStackH
        return height
    }
    
    /// 构造顶部按钮
    private func makeButton(title: String, imageName: String) -> WmcStyleButton {
        let btn = WmcStyleButton(style: .imageTop, space: 2.0)
        btn.setTitleColor(UIColor.wmc_grayH2_323233, for: .normal)
        btn.setTitleColor(disableColor, for: .disabled)
        btn.titleLabel?.font = 13.wmc_scaleFont()
//        btn.setImage(imageName.wmc_image, for: .normal)
        set(image: imageName.wmc_image, for: btn)
        btn.setTitle(title, for: .normal)
        return btn
    }
    
    private func set(image: UIImage, for button: WmcStyleButton) {
        button.setImage(image.yp.set(tintColor: UIColor.wmc_black85), for: .normal)
        button.setImage(image.yp.set(tintColor: disableColor), for: .disabled)
    }
    
    /// 切换延时拍照状态
    private func switchDelayTime() {
        let new = delayTime.rawValue
        if let newCase = DelayTime(rawValue: new + 1) {
            delayTime = newCase
        } else {
            delayTime = .none
        }
    }
    
    /// 切换清晰度
    private func switchArticulation() {
        let new = articulation.rawValue
        if let newCase = YPGEVideoBuffer.Articulation(rawValue: new + 1) {
            articulation = newCase
        } else {
            articulation = ._540p
        }
    }
    /// 刷新顶部按钮
    private func reloadTopActions() {
        var actions: [Action] = [.aspect, .delay(time: self.delayTime), .resolution]
        switch functionMode {
        case .photo: // 拍照
            break
        case .video: // 视频
            actions = [.delay(time: self.delayTime), .articulation(value: self.articulation)]
        default:
            break
        }
        reloadTopButtons(with: actions)
    }
    
    private func reloadTopButtons(with actions: [Action]) {
        var buttons: [WmcStyleButton] = []
        actions.forEach { action in
            switch action {
            case .aspect:
                buttons.append(aspectRatioBtn)
            case .delay(_):
                buttons.append(delayBtn)
            case .resolution:
                buttons.append(resolutionBtn)
            case .articulation:
                buttons.append(articulationBtn)
            default: break
            }
        }
        if case .photoAndCombine = functionMode {
            aspectRatioBtn.isEnabled = false
            resolutionBtn.isEnabled = false
        } else{
            aspectRatioBtn.isEnabled = true
            resolutionBtn.isEnabled = true
        }
        topStackView.yp.arrangedSubviews = buttons
    }
    /// 刷新底部按钮
    private func reloadBottomActions() {
        var actions: [Action] = [.joinGroup, .album]
        if isSubscribed {
            actions = [.invite, .album]
        }
        reloadBottomButtons(with: actions)
    }
    private func reloadBottomButtons(with actions: [Action]) {
        var buttons: [WmcSettingBusinessItemView] = []
        actions.forEach { action in
            switch action {
            case .invite:
                buttons.append(inviteItemView)
            case .joinGroup:
                buttons.append(joinItemView)
            case .album:
                buttons.append(albumItemView)
            default: break
            }
        }
        bottomStackView.yp.arrangedSubviews = buttons
    }
}
